<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
<link rel="stylesheet" href="./bootstrap-3.3.4-dist/css/bootstrap.min.css">

<!-- script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-gl/dist/echarts-gl.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-stat/dist/ecStat.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/extension/dataTool.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/map/js/china.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/map/js/world.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/extension/bmap.min.js"></script -->

<script type="text/javascript" src="./echarts.min.js"></script>
<script type="text/javascript" src="k-line.js"></script>
	   
<script src="./angular.min.js"></script>
<!--script src="./require.min.js"></script-->
<script src="./jquery-1.11.0.min.js"></script>
<script src="stock.js"></script>
<script src="filter.js"></script>

<script src="https://imgcache.qq.com/qcloud/tcbjs/1.3.2/tcb.js"></script>

<meta name="viewport" content="width=device-width, initial-scale=1">


<script>
/*
	var app = tcb.init({
		env: 'comnet'
	})
  
	app.callFunction({
		// 云函数名称
		name: 'add',
		// 传给云函数的参数
		data: {
			a: 1,
			b: 2,
		},
	})
	.then(res => {
		console.log(res.result) // 3
	})
	.catch(console.error);
*/
</script>

</head>
<body ng-app="myApp">
<div class="container-fluid" ng-controller="ctrl">
	<hr>
		<form class="form-inline">
			<input class="form-control" style="width:60%;" autocomplete="on" type="text" ng-model="query_str"></input>
			<button class="btn btn-primary form-control" ng-click="wencai()">问财取股票</button>
			<a target="_blank" href="http://m.iwencai.com/"> 问财</a>
		</form>
		<span ng-repeat="opt in options">
			<button class="btn btn-default" ng-click="wencai_str(opt)">{{opt}}</button>
		</span>
	<hr>
		<span ng-repeat="func in funcs">
			<button class="btn" ng-class="getSelect($index)?'btn-primary':'btn-default'"
				ng-click="setSelect($index)">{{func.name}}</button>
		</span>
		<button class="btn btn-warning" ng-click="edit()">编辑</button>
		<button class="btn btn-warning" ng-click="add_case()">添加</button>
		<textarea ng-show="filter.show" style="width:100%;height:300px;" ng-model="filter.func"></textarea>
		<textarea ng-show="filter.show_add" style="width:100%;height:300px;" ng-model="filter.add_case"></textarea>
	<hr>
		<button class="btn btn-success" ng-click="run()">选股</button>
		<button class="btn btn-danger" ng-click="search=false;">停止</button>
		<!--span>实时: <input Type="checkbox" ng-model="bRelTime"></input></span>
		<span>画图: <input Type="checkbox" ng-model="cond.showPic"></input></span>
		<span>指数比较: <input Type="checkbox" ng-model="cond.showIndex"></input></span-->
		<button class="btn" ng-class="bRelTime?'btn-primary':'btn-default'" ng-click="bRelTime=!bRelTime;">实时</button>
		<button class="btn" ng-class="cond.showPic?'btn-primary':'btn-default'" ng-click="cond.showPic=!cond.showPic;">IMG图</button>
		<button class="btn" ng-class="cond.showSvg?'btn-primary':'btn-default'" ng-click="cond.showSvg=!cond.showSvg;">SVG图</button>
		<button class="btn" ng-class="cond.showSelect?'btn-primary':'btn-default'" ng-click="cond.showSelect=!cond.showSelect;">只看选中</button>
		<!--button class="btn" ng-class="cond.showIndex?'btn-primary':'btn-default'" ng-click="cond.showIndex=!cond.showIndex;">指数比较</button-->
		<span>
			<span> | 显示</span>
			<input style="width:40px;" type="text" ng-model="cond.max_svg"></input>
			<span>个</span>
		</span>
		<span> | 股票数:{{count}}/{{all}}</span>
		<span> | 选中:{{select.length}}</span>
		<button class="btn btn-success" ng-click="distribute()">收益分布</button>
		<button class="btn btn-success" ng-click="loop_back()">回测</button>
		<span>
			<span> | 回测</span>
			<input style="width:40px;" type="text" ng-model="skip_day"></input>
			<span>日</span>
		</span>
		<button class="btn btn-warning" ng-click="edit_sort()">回测条件</button>
		<textarea ng-show="cond.show_sort" style="width:100%;height:300px;" ng-model="cond.edit_newHigh_func"></textarea>
		<div ng-if="cond.showBar" style="position: relative;">
			<ws-bar stocks=all_stock select=select out=bar_select></ws-bar>
			<div ng-repeat="e in bar_select" class="well col-md-6 pull-left" ng-mouseenter="e.hidePic=false;" >
				<div class="text-overflow">
					<button class="btn" ng-class="e.hidePic?'btn-default':'btn-info'" ng-click="e.hidePic=!e.hidePic;">{{e.id}}</button>
					<button class="btn" ng-class="e.use?'btn-primary':'btn-default'" ng-click="e.selectd=!e.selectd;"
						 ng-mouseenter="e.showIndex=true" ng-mouseleave="e.showIndex=false">{{e.info.name}}</button>
					<span class="text-primary"> {{$index}} | {{e.name}} </span> 
					<span ng-show="e.showIndex" style="position:absolute;left:10px;top:60px;">题材:{{e.info.index}}</span>
					<button class="btn btn-link" ng-click="calc(e.id);">重算</button>
					<span> | 成交 {{(e.vol * e.cur / 100000000) | number : 2}} 亿</span>
					<span> | 涨幅 {{e.radio * 100 | number : 2}} </span>
					<span> | 冲高 {{e.new_high * 100 | number : 2}} </span>
					<span ng-if="e.max_high"> | 回测冲高 {{e.max_high * 100 | number : 2}} </span>
					<span> | 因子 {{e.use}} </span>
				</div>
				<div ng-if="e.error">
					{{e.error}}
				</div>
				<div ng-if="e.hidePic ? false : (cond.showPic || cond.showSvg)">
					<div ng-if="cond.showPic">
						<img ng-src="http://image.sinajs.cn/newchart/daily/n/{{e.id}}.gif?r={{runTime}}" width="100%"/>
					</div>
					<div ng-if="cond.showSvg" style="position: relative;">
						<ws-kline stock=e></ws-kine>
					</div>
				</div>
			</div>
		</div>
	<hr>
	<hr ng-show="filter.show">
	<div class="row" ng-if="!cond.showBar">
	<div ng-repeat="e in select" class="well col-md-6 pull-left" ng-if="cond.showSelect ? e.selectd : true" ng-mouseenter="e.hidePic=false;" >
		<div class="text-overflow">
			<button class="btn" ng-class="e.hidePic?'btn-default':'btn-info'" ng-click="e.hidePic=!e.hidePic;">{{e.id}}</button>
			<button class="btn" ng-class="e.selectd?'btn-primary':'btn-default'" ng-click="e.selectd=!e.selectd;"
				 ng-mouseenter="e.showIndex=true" ng-mouseleave="e.showIndex=false">{{e.info.name}}</button>
			<span class="text-primary"> {{$index}} | {{e.name}} </span> 
			<span ng-show="e.showIndex" style="position:absolute;left:10px;top:60px;">题材:{{e.info.index}}</span>
			<span> | 成交 {{(e.vol * e.cur / 100000000) | number : 2}} 亿</span>
			<span> | 涨幅 {{e.radio * 100 | number : 2}} </span>
			<span> | 冲高 {{e.new_high * 100 | number : 2}} </span>
			<span ng-if="e.max_high"> | 回测冲高 {{e.max_high * 100 | number : 2}} </span>
		</div>
		<div ng-if="e.hidePic ? false : (cond.showPic || cond.showSvg)">
			<div ng-if="cond.showPic">
				<img ng-src="http://image.sinajs.cn/newchart/daily/n/{{e.id}}.gif?r={{runTime}}" width="100%"/>
				<!--img ng-src="http://image.sinajs.cn/newchart/min/n/{{e.id}}.gif" width="100%"/-->
			</div>
			<div ng-if="cond.showSvg" style="position: relative;">
				<ws-kline stock=e></ws-kine>
			</div>
		</div>
	</div>
	</div>
 
</div><!-- container -->

<script>

var app = angular.module('myApp', []);

var _data = {};
var _day = {};
var _info = {};
var _trim;
var query_str;
var _wencai_stock;
var _scope;

var _STOCK_HEADER = {
	"0" : "sz",
	"1" : "sz",
	"2" : "sz",
	"3" : "sz",
	"5" : "sh",
	"6" : "sh",
	"9" : "sh",
	"4" : ""
};

var BASE_KLINE = 240;
var BASE_DIV = 240 / BASE_KLINE;

function callCond(data){
	if (data && data.data && data.data.condition){
		$.ajax({
			dataType: "jsonp",
			jsonpCallback : "callParse",
			url: "http://m.iwencai.com/unified-wap/get-parser-data?callback=callParse&w=" 
				+ query_str + "&condition=" + encodeURIComponent(JSON.stringify(data.data.condition))
		}).fail(function(){
			alert("问财查询数据失败");
			window.open("http://m.iwencai.com/");
		});
	}else{
		alert(JSON.stringify(data));
		window.open(data.redirect_url || "http://m.iwencai.com/");
	}
}

function callParse(data){
	console.log(["call", data, data.data.token]);
	$.ajax({
		dataType: "jsonp",
		jsonpCallback : "callAll",
		url: "http://m.iwencai.com/unified-wap/cache?page=0&callback=callAll&perpage="
			+ data.data.analyze_data.total + "&token=" + data.data.token
	}).fail(function(){
		alert("问财获取全部数据失败");
		window.open("http://m.iwencai.com/");
	});
}

function callAll(data){
	_wencai_stock = data.data.data;
	_scope && _scope.$apply();
	for (var i in _wencai_stock) {
		var key = _wencai_stock[i];
		if (key){
			id = (_STOCK_HEADER[key['hqCode'].slice(0,1)]||"") + key['hqCode'];
			_info[id] = {
				name : key['股票简称'] || key['基金简称'] ,
				index : (key['所属概念'] || "").split(/;|；/img),
				new_price : key['最新价'] || key['基金@最新单位净值']
			}
			//getStock(id)
		}
	}
	console.log(["callAll 问财数据", data, _wencai_stock, _info]);
}

// DB
var _DB_ = window.indexedDB.open("stock");
var _indexedDB;
var initDBCnt = 0;
function initDB(event) {
	_indexedDB = event.target.result;
	var objectStore;
	if (!_indexedDB.objectStoreNames.contains('stock')) {
		objectStore = _indexedDB.createObjectStore('stock', { keyPath: 'id' });
	}else{
		// 初始化数据
		//return;
		objectStore = _indexedDB.transaction('stock').objectStore('stock');
		objectStore.openCursor().onsuccess = function (event) {
			var cursor = event.target.result;
			if (cursor) {
				_data[cursor.key] = cursor.value.data;
				_data[cursor.key].cache = true;
				++initDBCnt;
				//console.log(['缓存加载', cursor.key, cursor.value, initDBCnt]);
				cursor.continue();
			} else {
				console.log(['初始化缓存完成', initDBCnt]);
			}
		};
	}
}

_DB_.onsuccess = initDB;
_DB_.onupgradeneeded = initDB;

_DB_.onerror = function (event) {
	console.log('数据库打开报错:' + event);
};

function getStock(id, func) {
	
	var transaction = _indexedDB.transaction(['stock']);
	var objectStore = transaction.objectStore('stock');
	var request = objectStore.get(id);

	request.onerror = function(event) {
		console.log(id + ' 事务失败');
	};

	request.onsuccess = function( event) {
		if (request.result) {
			_data[id] = request.result.data;
			_data[id].cache = true;
			console.log(['缓存加载', id, request.result]);
		} else {
			console.log(id + ' 未获得数据记录');
		}
	};
}

function setStock(id, data) {
	if (data.cache) {
		return;
	}
	
	var request = _indexedDB.transaction(['stock'], 'readwrite')
		.objectStore('stock')
		.put({
			id : id,
			data : data
		});

	request.onsuccess = function (event) {
		console.log(id + ' 数据更新成功');
	};

	request.onerror = function (event) {
		console.log(id + ' 数据更新失败');
	}
}

var klineArr = [];
var klineMap = {};

function addKline(id, force) {
	if (klineArr.length >= (parseInt(_scope.cond.max_svg) || 10)){
		if (force){
			var i = klineArr.shift();
			delete klineMap[i]
		}else{
			return;
		}
	}
	klineArr.push(id);
	klineMap[id]=id;
}
	
app.directive("wsKline", function() {

	function check(id){
		return null != klineMap[id];
	}
	
    return {
        restrict : "EA",
		scope : { 
			stock : "="
		},
        link : function (scope, el, attr){
			var dom = el[0];
			$(dom).css("width", $(dom).parent().width());
			$(dom).css("height", 400);
			addKline(scope.stock.id);

			scope.$watch(
				function(){
					return scope.stock.hidePic;
				}, 
				function(n){
					//console.log(["hidePic", scope.stock.id, n]);
					if (false == n){
						addKline(scope.stock.id, true);
					}
				}
			);
			
			scope.$watch(
				function(){
					return check(scope.stock.id);
				}, 
				function(n){
					//console.log(["check", scope.stock.id, n]);
					if (n){
						kLine(dom, scope.stock);
					}else {
						scope.stock.hidePic = true;
					}
				}
			);
		}
    };
});

app.directive("wsAutoshow", function() {
    return {
        restrict : "EA",
		scope : { 
			stock : "="
		},
        link : function (scope, el, attr){
			return;
			var dom = el[0];
			$(dom).mouseenter(function() {
				var div = $(dom).offset();
				var win = $(window);
				
				var cur = scope.stock.hidePic;
				
				if (div.top >= win.scrollTop() && div.top < (win.scrollTop() + win.height())) {
					addKline(scope.stock.id, true);
					scope.stock.hidePic = false;
				}else {
					scope.stock.hidePic = true;
				}
				
				console.log([scope.stock.id, scope.stock.hidePic, div, $(dom).scrollTop(), win.scrollTop(), win.height(), scope.stock])
				scope.$digest();
			});
		}
    };
});

app.directive("wsIndex", function() {
    return {
        restrict : "EA",
		scope : { 
			index : "="
		},
        link : function (scope, el, attr){
			var dom = el[0];
			$(dom).css("width", $(dom).parent().width());
			$(dom).css("height", 700);
			Index(dom, scope.index);
		}
    };
});

app.directive("wsBar", function($rootScope) {
    return {
        restrict : "EA",
		scope : { 
			stocks : "=",
			select : "=",
			out : "="
		},
        link : function (scope, el, attr){
			var dom = el[0];
			$(dom).css("width", $(dom).parent().width());
			$(dom).css("height", 360);
			
			scope.$watch(attr.stocks, function(n){
				var out = Bar(dom, scope.select, scope.stocks);
				out.chart.on('click', function (params) {
					console.log("wsBar", params, out.map[parseFloat(params.name)*2]);
					//$rootScope.bar_select = out.map[parseFloat(params.name)*2];
					scope.out = out.map[parseFloat(params.name)*2];
					$rootScope.$digest();
				});
			});
		}
    };
});

app.controller('ctrl', function($scope, $http, $sce) {
	_scope = $scope;
	
	$scope._XSS = $sce.trustAsResourceUrl;
	
	$scope.cond = {
		max_svg : 10,
		showBar : false
	}
	
	
	$scope.query_str = "";
	$scope.skip_day = 0;
	$scope.wencai = function(){		
		query_str = $scope.query_str;
		$scope.search = false;
		try{
			$.ajax({
				dataType: "jsonp",
				jsonpCallback : "callCond",
				url: "http://m.iwencai.com/unified-wap/get-base-data?callback=callCond&w=" 
					+ $scope.query_str
			}).fail(function(){
				alert("问财查询失败");
			});
		}catch(e){
			alert("问财查询失败");
		}
	}
	$scope.wencai_str = function(s){
		$scope.query_str = s + ";所属概念";
		$scope.wencai();
	}
	
	function getStockId(i){
		var id = i;
		if (_wencai_stock && _wencai_stock.length){
			var key = _wencai_stock[i];
			if (key){
				id = (_STOCK_HEADER[key['hqCode'].slice(0,1)]||"") + key['hqCode'];
			}else{
				// 返回空退出循环控制
				return;
			}
		}
		return id;
	}
	
	var _new_high_function = function(data, last){
		try{
			var new_high = 0;
			var cnt = last.length;
			if (cnt > 3) cnt = 3;
			for (var j = 0; j < cnt; j++){
				var e = last[j];
				if (e.high > new_high){
					new_high = e.high;
				}
			}
			
			if (new_high > 0){
				var base = data[data.length-1].high;
				new_high = (new_high - base)/base;
			}else{
				new_high = (data[data.length-1].high/data[data.length-1].open)-1;
			}
			return new_high;
		}catch(e){
			console.log(e);
			return 0;
		}
	}
	/*
	获取股票详细数据，递归获取。
	i _stock列表下标
	all 不为0获取全部数据，all为模值
	*/
	function getStockData(i = 0, all = 0){
		var id = _stock[i];
		var name = id;
		/*
		if (_wencai_stock && _wencai_stock.length){
			var key = _wencai_stock[i];
			if (key){
				name = key['股票简称'];
				key = key['股票代码'].split(".");
			}else{
				return;
			}
			id = key[1].toLocaleLowerCase() + key[0];
		}
		*/
		id = getStockId(i)
		
		if (!all){
			// 直接查询场景
			id = i;
		}
		
		if (!id){
			return;
		}
		
		function finish(data, status) {
			if (all && $scope.search){
				$scope.count++;
				i += parseInt(all) || 1;
				getStockData(i, all);
			}
			
			if (!(_data[id] && _data[id].length)){
				return;
			}
			
			setStock(id, _data[id]);
			
			/*
			http://w.sinajs.cn/callback=/?list=sh600000		
			var hq_str_sh600000="浦发银行,12.970,13.020,12.910,13.060,12.880,12.910,12.920,18030024,233306762.000,48374,12.910,272705,12.900,429135,12.890,950162,12.880,372000,12.870,40700,12.920,49012,12.930,135400,12.940,66500,12.950,55600,12.960,2018-01-16,10:24:10,00";
			var 代码 =“证券简称,今日开盘价,昨日收盘价,最近成交价,最高成交价,最低成交价,买入价,卖出价,成交数量,成交金额,买数量一,买价位一,买数量二,买价位二,买数量三 ,买价位三,买数量四,买价位四,买数量五,买价位五,卖数量一,卖价位一,卖数量二,卖价位二,卖数量三,卖价位三,卖数量四,卖价位四,卖数量五,卖价位五,行情日期,行情时间,停牌状态”

			停牌状态为"03"时就是股票停牌了，为"00"表示正常
			*/
			if ($scope.bRelTime){
				var cur;
				eval("cur = hq_str_" + id + ".split(',')");
				_day[id] = combData(_data[id], cur);
			}else{
				if (null == _day[id]) {
					_day[id] = combData(_data[id]);
				}
			}
			
			// 计算结果
			var out = calc(id);
			
			$scope.all_stock.push(out);
			if (out.use){
				$scope.select.push(out);
			}
		}
		
		$scope.calc = calc;
		function calc(id){
			if (typeof _trim != "function"){
				return;
			}
			
			try{
				var skip = parseInt($scope.skip_day) || 0;
				var use = [];
				var new_high = 0;
				var data;
				if (skip > 0){
					data = _day[id].slice(0, 0-skip);
					new_high = _new_high_function(data, _day[id].slice(0-skip));
					use = _trim(id, data, _data[id].slice(0, 0-(skip*BASE_DIV)), BASE_DIV, name);
				}else{
					data = _day[id];
					new_high = _new_high_function(data, []);
					use = _trim(id, data, _data[id], BASE_DIV, name);
				}
				
				var out = {
					id : id, 
					info : _info[id],
					name : data[data.length-1].day,
					vol : data[data.length-1].volume,
					cur : data[data.length-1].close,
					radio : data[data.length-1].radio,
					new_high : new_high,
					use : use,
					day : _day[id], // 原始数据汇聚的日线
					min : _data[id], // 原始数据（按分钟取）
					skip : skip
				}
				
				return out;
			}catch(e){
				return {
					id : id, 
					info : _info[id],
					name : data[data.length-1].day,
					vol : data[data.length-1].volume,
					cur : data[data.length-1].close,
					radio : data[data.length-1].radio,
					use : true,
					error : e
				}
			}
		}
		
		function current(){
			$http.jsonp("http://w.sinajs.cn/?r=" + $scope.runTime + "&list=" + id).
				success(finish).error(finish);
		}
			
		if (_data[id] && _info[id] && (parseFloat(_data[id][_data[id].length-1].close) == parseFloat(_info[id].new_price))){
			if ($scope.bRelTime){
				current();
			}else{
				setTimeout(function(){
					finish();
					$scope.$digest();
				}, 0);
			}
		}else{
			var h = $http.jsonp("http://money.finance.sina.com.cn/quotes_service/api/jsonp_v2.php/_data['" 
				+ id + "']=/CN_MarketData.getKLineData?symbol=" + id 
				+ "&scale=" + BASE_KLINE + "&datalen=" + (240 * BASE_DIV));
			if ($scope.bRelTime){
				h.success(current).error(current);
			}else{
				h.success(finish).error(finish);
			}
			
		}
	}

	function combData(data, cur){
		var out = [];
		try {
		for (var i = 0; i < data.length; ){
			var e = data[i];
			/*
			{
			day: "2017-03-09 10:45:00",
			open: "41.170",
			high: "41.260",
			low: "41.160",
			close: "41.240",
			volume: "92200",
			ma_price5: 41.324,
			ma_volume5: 242366
			}
			*/
			var temp = {
				day : e.day.split(" ")[0],
				open : parseFloat(e.open)||0,
				high : parseFloat(e.high)||0,
				low : parseFloat(e.low)||0,
				volume : 0,
				last : data[i-1] ? parseFloat(data[i-1].close)||0 : (parseFloat(e.close)||0),
				last_high : data[i-1] ? parseFloat(data[i-1].high)||0 : (parseFloat(e.close)||0),
				ma_price5 : 0,
				ma_volume5 : 0,
				ma_price10 : 0,
				ma_volume10 : 0,
				ma_price30 : 0,
				ma_volume30 : 0,
			};

			for (var j = 0; j < BASE_DIV && i < data.length; j++, i++){
				e = data[i];
				temp.close = parseFloat(e.close)||0;
				var h = parseFloat(e.high)||0, l = parseFloat(e.low)||0;
				if (h > temp.high) temp.high = h;
				if (l < temp.low) temp.low = l;
				temp.volume += parseFloat(e.volume)||0;
				temp.ma_price5 += parseFloat(e.ma_price5)||0;
				temp.ma_volume5 += parseFloat(e.ma_volume5)||0;
				temp.ma_price10 += parseFloat(e.ma_price10)||0;
				temp.ma_volume10 += parseFloat(e.ma_volume10)||0;
				temp.ma_price30 += parseFloat(e.ma_price30)||0;
				temp.ma_volume30 += parseFloat(e.ma_volume30)||0;
			}
			
			temp.radio = (temp.close - temp.last)/temp.last;
			temp.ma_price5 /= BASE_DIV;
			temp.ma_volume5 /= BASE_DIV;
			temp.ma_price10 /= BASE_DIV;
			temp.ma_volume10 /= BASE_DIV;
			temp.ma_price30 /= BASE_DIV;
			temp.ma_volume30 /= BASE_DIV;
			out.push(temp);
		}
		
		if (cur){
			var last = out[out.length-1];
			var n = {
				day : cur[30],
				open : parseFloat(cur[1])||0,
				close : parseFloat(cur[3])||0,
				high : parseFloat(cur[4])||0,
				low : parseFloat(cur[5])||0,
				volume : parseFloat(cur[8])||0,
				last : parseFloat(cur[2])||0,
				ma_price5 : last.ma_price5,
				ma_volume5 : last.ma_volume5,
				ma_price10 : last.ma_price10,
				ma_volume10 : last.ma_volume10,
				ma_price30 : last.ma_price30,
				ma_volume30 : last.ma_volume30,
			};
			
			n.radio = (n.close - n.last)/n.last;
			
			n.ma_price5 = (last.ma_price5 * 4 + n.close) / 5;
			n.ma_volume5 = (last.ma_volume5 * 4 + n.volume) / 5;
			n.ma_price10 = (last.ma_price10 * 9 + n.close) / 10;
			n.ma_volume10 = (last.ma_volume10 * 9 + n.volume) / 10;
			n.ma_price30 = (last.ma_price30 * 29 + n.close) / 30;
			n.ma_volume30 = (last.ma_volume30 * 29 + n.volume) / 30;
			
			if (n.day > last.day){
				out.push(n);
			}
		}
		
		}catch(e){
			console.log(data, temp, e);
		}
		return out;
	}

	$scope.select = [];
	$scope.all_stock = [];
	$scope.count = 0;
	
	$scope.funcs = _filter;
	$scope.options = _options;
	
	$scope.filter = $scope.funcs[0];
	
	$scope.getSelect = function($index){
		return $scope.funcs[$index].selectd;
		//return $scope.filter==$scope.funcs[$index];
	}
	$scope.setSelect = function($index){
		$scope.filter=$scope.funcs[$index];
		$scope.funcs[$index].selectd = !$scope.funcs[$index].selectd;
	}
	
	$scope.edit = function(){
		$scope.filter.show = !$scope.filter.show;
		if ($scope.filter.show){
		}else{
			if (typeof $scope.filter.func != "function"){
				console.log($scope.filter.func);
				$scope.filter.func = eval("$scope.filter.func=" + $scope.filter.func);
			}
		}
	}
	
	$scope.add_case = function(){
		$scope.filter.show_add = !$scope.filter.show_add;
		if ($scope.filter.show_add){
			$scope.filter.add_case = "{\nname : '',\nfunc : function(id, day, min, div, name){\nreturn true;\n}\}"
		}else{
			$scope.filter.add_case = eval("$scope.filter.add_case=" + $scope.filter.add_case);
			$scope.funcs.push($scope.filter.add_case);
		}
	}
	
	$scope.edit_sort = function(){
		$scope.cond.show_sort = !$scope.cond.show_sort;
		$scope.cond.edit_newHigh_func=_new_high_function;
		if ($scope.cond.show_sort){
			
		}else{
			if (typeof $scope.cond.edit_newHigh_func != "function"){
				console.log($scope.cond.edit_newHigh_func);
				_new_high_function = eval("$scope.cond.edit_newHigh_func=" + $scope.cond.edit_newHigh_func);
			}
		}
	}
	
	$scope.$watch(function(){
		return _wencai_stock ? _wencai_stock.length : (_stock.length || 0)
	}, function(n, o){
		$scope.all = n;
	});

	$scope.distribute = function(){
		$scope.cond.showBar=!$scope.cond.showBar;
		if ($scope.cond.showBar){
			//getIndex();
		}
	}
	
	$scope.loop_back = function(){
		var skip = parseInt($scope.skip_day) || 0;
		skip++;
		$scope.skip_day = skip;
		$scope.run();
	}
	

	$scope.run = function(){
		if (($scope.search) && ($scope.count < $scope.all)){
			return;
		}
		
		$scope.bRelTime ? $scope.runTime = (new Date()).valueOf() : $scope.runTime = (new Date()).toDateString();
		
		klineArr = [];
		klineMap = {};
		
		$scope.select = [];
		$scope.all_stock = [];
		$scope.count = 0;
		$scope.search = true;
		$scope.cond.showBar = false;
		//_trim = $scope.filter.func;
		_trim = function(id, day, min, div, name){
			var v = [];
			for (var i=0; i < $scope.funcs.length; i++){
				var f = $scope.funcs[i];
				if (f.selectd){
					var ret = f.func(id, day, min, div, name);
					if (!ret){
						return null;
					}
					v.push(f.name + ":" + ret);
				}
			}
			return v;
		}

		// 多线程并行分析
		getStockData(0, 5);
		getStockData(1, 5);
		getStockData(2, 5);
		getStockData(3, 5);
		getStockData(4, 5);
	}
	
	function getIndex(){
		$scope.select = [];
		$scope.all_stock = [];
		for (var i = 0; i < _index.length; i++){
			getStockData(_index[i][0]);
		}
	}
	
	// 初始化问财选股
	$scope.wencai_str("全部股票");
	var d = new Date();
	$scope.bRelTime = (d.getDay() >= 1) && (d.getDay() <= 5) 
		&& (d.getHours() >= 9) && (d.getHours() <= 16);
});
</script>


</body>
</html>